package com.qidian.zl.paper.test;

import com.qidian.zl.paper.factory.ServiceFactory;
import com.qidian.zl.paper.pojo.Field;
import com.qidian.zl.paper.service.FieldService;
import com.qidian.zl.paper.util.Data;
import com.qidian.zl.paper.util.JsonTools;
import com.qidian.zl.paper.util.StResult;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//@WebServlet("/saveField")
public class FieldAddServlet extends HttpServlet {
    private FieldService fieldService= ServiceFactory.getFieldService();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        StResult result = null;
        Long   fieldId=-1l;
        Long paperId = -1L;
        try{
            fieldId = new Long(request.getParameter("fieldId"));
        }catch (Exception e){}
        try {
            paperId = new Long(request.getParameter("paperId"));
        } catch (Exception e) {}

        if(paperId==-1){
            result = new StResult(Data.RESPONSE_UNABLE,"请先保存问卷");
        }else {
            String fieldTitle = request.getParameter("fieldTitle");
            if (fieldTitle==null||"".equals(fieldTitle)){
                result = StResult.fail("字段名称不能为空");
            }else {
                int fieldType = -1;
                try {
                    fieldType = Integer.parseInt(request.getParameter("fieldType"));
                } catch (Exception e) { }

                if (fieldType == -1) {
                    result = StResult.fail("字段保存失败");
                }else {
                    String fieldDesc = request.getParameter("fieldDesc");
                    String[] selectorTexts = null;
                    if (fieldType == 4 || fieldType == 5) {
                        selectorTexts = request.getParameterValues("selectorText");
                    }

                    Field field=new Field();
                    field.setFieldId(fieldId);
                    field.setFieldName(fieldTitle);
                    field.setFieldType(fieldType);
                    field.setPaperId(paperId);
                    field.setFieldDesc(fieldDesc);
                    System.out.println(field);
                    fieldId= fieldService.saveOrUpdate(field,selectorTexts);
                    result = StResult.ok(""+fieldId);
                }
            }
        }

            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JsonTools.obj2String(result));

        }




    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
